import tinymce from 'tinymce/tinymce'
import { v4 as uuid } from 'uuid'
import { 
  getParentNumber, 
  resetItemListSiblingsNumber, 
  getNumber,
  getValue
} from './itemlistSetting'
import { checkBeforeInsert } from '@/utils/helpers'
import { insertElementAfterBlock } from '@/utils/dom'
import { Message } from 'element-ui'

tinymce.PluginManager.add('itemlist', function (editor) {
  const _CLASSNAME = 'item_list '
  
  const onAction = (command) => {
    const validate = checkBeforeInsert('item_list')
    if (!validate) return
    // 此处判断新增列项的前置条件
    editor.execCommand('toggleItemList', false, command)
  }

  editor.on('keyup', (event) => {
    const node = editor.selection.getNode()
    const prevNode = node?.previousSibling
    const isItemList = prevNode?.classList?.contains('item_list')
    if (isItemList && "Enter" === event.key) {
      console.log('---PluginManager itemlist keyup---')
      const number = getNumber({
        node, 
        classList: prevNode.className.replace('item_list', '').trim().split(' '),
        dataLang: prevNode.dataset.lang
      })
      const level = parseInt(node.getAttribute('data-level'))
      const value = getValue(level, number)
      const parentNumber = getParentNumber(prevNode, level)
      // 从列项x所在行按住enter，下一行列项x的编号+1
      editor.dom.setAttribs(node, {
        'data-type': 'item_list',
        'class': prevNode.className,
        'data-number': number,
        'data-value': value,
        'data-level-num': `${level > 1 ? parentNumber + '.' : ''}${number}`,
        'data-id': uuid(),
        'data-note-id': uuid(),
        'data-block-id': prevNode.dataset.blockId,
        'data-block-data-id': prevNode.dataset.blockDataId,
        'data-lang': prevNode.dataset.lang
      })
      
      // 重置紧邻的连续编号
      resetItemListSiblingsNumber(node, editor, prevNode.dataset.lang)
    } else if(('Delete' === event.key || 'Backspace' === event.key) && node.classList.contains('item_list')) {
      // 删除列项之后要刷新后面的编号
      resetItemListSiblingsNumber(prevNode || node, editor, prevNode?.dataset?.lang || node.dataset?.lang)
    }
  })

  editor.addCommand('toggleItemList', (ui, value) => {
    const node = editor.selection.getNode()
    if (node.dataset.type === 'table' || editor.dom.getParent(node, 'table')) {
      return Message.warning({
        message: `表格中暂不支持插入列项`,
        showClose: true
      })
    }
    if (editor.dom.getParent(node, 'div[data-type="figure"]')) {
      return Message.warning({
        message: `图结构化中暂不支持插入列项`,
        showClose: true
      })
    }
    const { action, level, dataLang } = value
    const className = _CLASSNAME + action + ' ' + dataLang

    if (node.classList?.contains('page_body')) {
      // 选择了多行数据
      console.log('editor.selection.start', editor.selection.getStart())
      console.log('editor.selection.end', editor.selection.getEnd())
      console.log('editor.selection.getNode', node)

      const firstNode = editor.selection.getStart()
      paragraphToItemList(firstNode, editor.selection.getEnd(), dataLang)
      return
    }
    let number
    if (node.dataset.lang !== dataLang) {
      if (level > 1) {
        const langLabel = dataLang === 'zh' ? '中文' : '英文'
        return Message.warning({
          message: `${level}级${langLabel}列项须添加在${level - 1}级${langLabel}列项之后`,
          showClose: true 
        })
      }
      number = 1
    } else {
      number = getNumber({ node, classList: [action], level, dataLang })
    }
    const parentNumber = getParentNumber(node, level)
    const parentLevel = parentNumber && parentNumber.split('.').length || 0
    if (level > 1 && parentLevel !== level - 1) {      
      return Message.warning({
        message: `${level}级列项须添加在${level - 1}级列项之后`,
        showClose: true
      })
    }
    const dataValue = getValue(level, number)
    const dataId = uuid()
    const blockId = uuid()
    const blockDataId = uuid()
    const config = {      
      'class': className,
      'data-value': dataValue,
      'data-number': number,
      'data-level-num': `${level > 1 ? parentNumber + '.' : ''}${number}`,
      'data-type': 'item_list',
      'data-level': level,
      'data-id': dataId,
      'data-note-id': uuid(),
      'data-action': action,
      'data-block-id': blockId,
      'data-block-data-id': blockDataId,
      'data-lang': dataLang
    }
    const currentContent = node.textContent.replace(/[\u200B-\u200D\uFEFF]/g, "")
    if (node.dataset.type === 'paragraph' && currentContent?.length === 0) {
      // 如果当前行是空的段落，就将当前行作为列项
      editor.dom.removeAllAttribs(node)
      editor.dom.setAttribs(node, config)
    } else {
      const content = editor.dom.create('p', config, '<br>')
      insertElementAfterBlock(content, editor)
      editor.selection.setCursorLocation(content, 0)
    } 
    // 重置紧邻的连续编号
    setTimeout(() => {
      resetItemListSiblingsNumber(node, editor, dataLang)
    }, 100)  
  })

  // P标签转换为列项
  function setPTagToItemList({node, className, number, level, dataValue, action, blockId, blockDataId, parentNumber, dataLang}) {
    // 当前行已经是P，将其变为列项
    editor.dom.removeAllAttribs(node)
    editor.dom.setAttribs(node, {
      'class': className,
      'data-type': 'item_list',
      'data-id': uuid(),
      'data-block-id': blockId,
      'data-note-id': uuid(),
      'data-block-data-id': blockDataId,
      'data-number': number,
      'data-level': level,
      'data-value': dataValue,
      'data-action': action,
      'data-level-num': `${level > 1 ? parentNumber + '.' : ''}${number}`,
      'data-lang': dataLang
    })
    if (node.textContent === '') {
      node.innerHTML = '<br>'
    }
  }

  // 选中多行段落切换为列项
  function paragraphToItemList(node, lastNode, dataLang) {
    if (node.nodeName === 'P') {
      setPTagToItemList({node, dataLang})
    }
  }

  return (
    editor.ui.registry.addMenuButton('itemlist', {
      icon: 'ordered-list',
      tooltip: '列项',
      fetch: function (callback) {
        callback([
          {
            type: 'menuitem',
            text: '字母a)b)【一级】',
            onAction: function () {
              onAction({ action: 'lower', level: 1, dataLang: 'zh' })
            }
          },
          {
            type: 'menuitem',
            text: '数字1)2)【二级】',
            onAction: function () {
              onAction({ action: 'num', level: 2, dataLang: 'zh' })
            }
          },
          {
            type: 'menuitem',
            text: '罗马I)II)【三级】',
            onAction: function () {
              onAction({ action: 'roman', level: 3, dataLang: 'zh' })
            }
          },
          // 四级列项需要改成数字[1][2]，无缩进，与列项数据结构区分开
          //{
          //  type: 'menuitem',
          //  text: '数字[1][2]【四级】',
          //  onAction: function () {
          //    onAction({ action: 'num2', level: 4, dataLang: 'zh' })
          //  }
          //}
        ])
      }
    }),
    {
      getMetadata: function () {
        return {
          name: '列项',
          url: 'http://sfrj.cn'
        }
      }
    }
  )
})
